package plus.xj17520.org.service.impl;

import cn.hutool.core.util.IdUtil;
import plus.xj17520.basic.domain.AjaxResult;
import plus.xj17520.basic.util.EmailUtil;
import plus.xj17520.basic.util.RedisService;
import plus.xj17520.org.domain.RegisterDTO;
import plus.xj17520.org.domain.Shop;
import plus.xj17520.org.mapper.EmployeeMapper;
import plus.xj17520.org.mapper.ShopMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import plus.xj17520.org.service.IShopService;

@Service
public class ShopServiceImpl implements IShopService {
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    EmailUtil emailUtil;
    @Autowired
    RedisService redisService;
    /**
     * 注册的业务层
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public AjaxResult register(RegisterDTO dto) {
        //手动校验手机号的格式:
//        String phone = dto.getEmployee().getPhone();
//        String rx = RegexPool.MOBILE;
        //1.需要新增商家
        //1.1新增的商家数据,它的state状态应该为1,待审核状态
        shopMapper.insertSelective(dto.getShop());

        //2.需要新增员工数据
        //2.1员工的对象,首先需要给他一个超管的标识
        dto.getEmployee().setShopAdmin(true);
        //2.2这个员工对象,还需要关联一个店铺id
        dto.getEmployee().setShopId(dto.getShop().getId());
        employeeMapper.insertSelective(dto.getEmployee());
        //这里就需要给这个管理员发送一个激活商家的邮件
        String uuid = IdUtil.fastSimpleUUID();
        redisService.setStringKeyAndValue( uuid,dto.getShop(),30);
        emailUtil.send( dto.getEmployee().getEmail(),"宠物乐园商家激活",
                "尊敬"+dto.getEmployee().getUsername()+"用户您好,请在30分钟之内前往该地址完成账号激活操作:"+"http://localhost/shop/state/"+uuid);
        return AjaxResult.me();
    }

    /**
     * 这里是给商户做激活的业务层
     * @param uuid
     * @return
     */
    @Override
    public AjaxResult state(String uuid) {
        //1.校验uuid是否伪造,1.有可能uuid是用户随便拼接的 ,还有可能为空 ,还有可能已经过期的
        //如果为true,通过验证
        if (redisService.hasKey(uuid)){
            //就需要改变商户的状态
            Shop shop = redisService.getKeyObjectValue(uuid, Shop.class);
            shop.setState(2);
            shopMapper.updateByPrimaryKeySelective(shop);
            return AjaxResult.me("当前账号已经激活,请去登录页面完成登录");
        }
        return AjaxResult.setMsg("当前链接已失效,请从新获取邮箱");
    }

    public static void main(String[] args) {
        String uuid = IdUtil.fastSimpleUUID();
        System.out.println(uuid);
    }
}
